

function mRequest(url,data) {
  const HOST = "https://api.keyikami.com/api/v1"
  let result = { code: ResultCode.kUnknownError}
  let response = http.postJson(HOST + url, data);
    if (response.statusCode !== 200) {
        result.code = response.statusCode
    } else {
        result = response.body.json()
    }
  return result
}

const ResultCode = {
    kSuccess: 0, // 请求成功
    kTooManyRequests: 429, // 请求过多，频繁的请求会导致返回此结果，如果出现此结果，请降低请求频率，否则会被服务器加入黑名单
    kUnknownError: 1000, // 未知错误，通常不会出现这种情况
    kInvalidSecretIdOrKey: 1001, // 无效的secretId或secretKey，secretId或secretKey错误
    kInvalidAccountOrPassword: 1002, // 无效的keyCard，keyCard错误，或者卡密不存在
    kAccountSuspended: 1003, // keyCard被禁用，卡密被冻结
    kInvalidProject: 1004, // 无效的软件ID，软件的ID错误，或者与卡密绑定的软件ID不匹配
    kInvalidTimestamp: 1005, // 无效的时间戳，时间戳需要当前时间，如果时间戳与当前时间超过5秒，则视为无效
    kInvalidMachineId: 1006, // 无效的machineId，机器码的格式不正确
    kInvalidSessionTokenOrKey: 1007, // 无效的sessionToken或verifyKey，通常不会出现这种情况
    kTooManyDevice: 1008, // 设备过多,当前登录的卡密的可登录设备数量达到上限
    kSessionLimit: 1009, // session限制，你的账号同时在线的会话数量达到上限
  
    // Cloud related error codes
    kInvalidCloudFunction: 1100, // 无效的云函数
    kCallException: 1101, // 调用异常
  
    // Account related error codes
    kAccountAlreadyExist: 1200, // 账号已存在
    kInvalidVerifyCode: 1201, // 无效的验证码
    kInvalidVerifyCodeType: 1202, // 无效的验证码类型
}

const getNowTime = () => {
    return Math.floor(Date.parse(new Date()) / 1000)
}

function KeYiSession(secretId,secretKey,projectId) {
  return {
      secretId:secretId,
      secretKey:secretKey,
      projectId:projectId,

      projectData:"",
      projectNotice:"",
      endDate:0,
      errorCode: 0,

      init(secretId,secretKey,projectId) {
          this.secretId = secretId
          this.secretKey = secretKey
          this.projectId = projectId
      },
      login(username,machineId,password = null) {
          let data = {
              secretId: this.secretId,
              secretKey:this.secretKey,
              projectId:this.projectId,
              username:username,
              machineId:machineId,
              password:password,
              timestamp:getNowTime()
          }
          let response = mRequest("/login",data)
          if (response.code !== ResultCode.kSuccess) {
              this.errorCode = response.code
              return false
          }
          this.sessionToken = response.sessionToken
          this.sessionKey = response.nextKey
          this.projectNotice = response.notice
          this.projectData = response.data
          this.endDate = response.endDate
          return true
      },
      tick() {
         let data = {
              secretId: this.secretId,
              secretKey: this.secretKey,
              sessionToken: this.sessionToken,
              key: this.sessionKey
          }
          let response = mRequest("/tick",data)
          if (response.code !== ResultCode.kSuccess) {
              this.errorCode = response.code
              return false
          } else {
              this.sessionKey = response.nextKey
              return true
          }
      },
      logout() {
          let data = {
              secretId: this.secretId,
              secretKey: this.secretKey,
              sessionToken: this.sessionToken,
              key: this.sessionKey
          }
          let response = mRequest("/logout",data)
          if (response.code !== ResultCode.kSuccess) {
              this.errorCode = response.code
              return false
          }
          return true
      },
      getValue(keys) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            sessionToken: this.sessionToken,
            keys: keys
        }
        let response = mRequest("/get_value",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return null
        }
        return response.values
      },
      setValue(maps) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            sessionToken: this.sessionToken,
            data: maps
        }
        let response = mRequest("/set_value",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return false
        }
        return true
      },
      call(method,args) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            sessionToken: this.sessionToken,
            method: method,
            args: args
        }
        let response = mRequest("/call",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return null
        }
        return response.data
      },
      getConfig() {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            sessionToken: this.sessionToken,
        }
        let response = mRequest("/get_config",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return null
        }
        return response.data
      },
      setConfig(data) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            sessionToken: this.sessionToken,
            data: data
        }
        let response = mRequest("/set_config",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return false
        }
        return true
      },
      _send_code(email,type) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            projectId: this.projectId,
            email: email,
            type: type
        }
        let response = mRequest("/send_verify_code",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return false
        }
        return true
      },
      sendRegisterCode(email) {
        return this._send_code(email,1)
      },
      sendResetPasswordCode(email) {
        return this._send_code(email,2)
      },
      registerAccount(email,password,nickname,verifyCode) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            projectId: this.projectId,
            email: email,
            password: password,
            nickname: nickname,
            verifyCode: verifyCode
        }
        let response = mRequest("/register_account",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return false
        }
        return true
      },
      resetPassword(email,password,verifyCode) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            projectId: this.projectId,
            email: email,
            password: password,
            verifyCode: verifyCode
        }
        let response = mRequest("/reset_password",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return false
        }
        return true
      },
      changePassword(email,password,newPassword) {
        let request = {
            secretId: this.secretId,
            secretKey: this.secretKey,
            projectId: this.projectId,
            email: email,
            password: password,
            newPassword: newPassword
        }
        let response = mRequest("/change_password",request)
        if (response.code !== ResultCode.kSuccess) {
            this.errorCode = response.code
            return false
        }
        return true
      }
  }
}

const keyi = KeYiSession()

module.exports = {
    keyi:keyi,
    ResultCode:ResultCode,
    Session:KeYiSession
}